<template>
  <div class="order-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">订单管理</h1>
      <div class="order-stats">
        <span class="total-count">共 {{ totalCount }} 条订单</span>
      </div>
    </div>

    <!-- 状态筛选标签 -->
    <div class="status-tabs">
      <button
        v-for="(statusInfo, status) in statusOptions"
        :key="status"
        class="status-tab"
        :class="{ active: currentStatus === parseInt(status) }"
        @click="changeStatus(parseInt(status))"
      >
        {{ statusInfo.text }}
        <span class="status-count" v-if="statusInfo.count > 0">({{ statusInfo.count }})</span>
      </button>
    </div>

    <!-- 订单列表 -->
    <div class="order-list">
      <div v-if="loading" class="loading-state">
        <div class="loading-spinner"></div>
        <p>加载中...</p>
      </div>

      <div v-else-if="list.length === 0" class="empty-state">
        <div class="empty-icon">📦</div>
        <p>暂无订单数据</p>
      </div>

      <div v-else class="list-content">
        <div v-for="item in list" :key="item.orderid" class="order-item">
          <div class="order-image">
            <img :src="item.img1" :alt="item.proname" />
          </div>
          <div class="order-info">
            <h3 class="product-name">{{ item.proname }}</h3>
            <div class="order-details">
              <span class="price">¥{{ item.originprice }}</span>
              <span class="status" :class="getStatusClass(item.status)">
                {{ getStatusText(item.status) }}
              </span>
            </div>
            <div class="order-id">订单号: {{ item.orderid }}</div>
            <div class="order-actions">
              <select
                class="status-select"
                :value="item.status"
                @change="updateOrderStatus(item.orderid, $event.target.value)"
              >
                <option value="0">未支付</option>
                <option value="1">待发货</option>
                <option value="2">待收货</option>
                <option value="3">待评价</option>
                <option value="4">已完成</option>
              </select>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 分页组件 -->
    <div class="pagination-container" v-if="totalCount > 0">
      <div class="pagination">
        <button
          class="page-btn prev-btn"
          :disabled="currentPage === 1"
          @click="changePage(currentPage - 1)"
        >
          上一页
        </button>

        <div class="page-numbers">
          <button
            v-for="page in visiblePages"
            :key="page"
            class="page-btn"
            :class="{ active: page === currentPage }"
            @click="changePage(page)"
          >
            {{ page }}
          </button>
        </div>

        <button
          class="page-btn next-btn"
          :disabled="currentPage === totalPages"
          @click="changePage(currentPage + 1)"
        >
          下一页
        </button>
      </div>

      <div class="pagination-info">
        <span>第 {{ currentPage }} 页，共 {{ totalPages }} 页</span>
        <select class="page-size-select" v-model="pageSize" @change="changePageSize">
          <option value="5">5条/页</option>
          <option value="10">10条/页</option>
          <option value="20">20条/页</option>
          <option value="50">50条/页</option>
        </select>
      </div>
    </div>
  </div>
</template>
<script>
import axios from 'axios'
export default {
  data() {
    return {
      list: [],
      loading: false,
      currentPage: 1,
      pageSize: 10,
      totalCount: 0,
      totalPages: 0,
      currentStatus: null, // 当前选中的状态，null表示全部
      statusOptions: {
        null: { text: '全部', count: 0 },
        0: { text: '未支付', count: 0 },
        1: { text: '待发货', count: 0 },
        2: { text: '待收货', count: 0 },
        3: { text: '待评价', count: 0 },
        4: { text: '已完成', count: 0 }
      }
    }
  },
  computed: {
    visiblePages() {
      const pages = []
      const start = Math.max(1, this.currentPage - 2)
      const end = Math.min(this.totalPages, this.currentPage + 2)

      for (let i = start; i <= end; i++) {
        pages.push(i)
      }
      return pages
    }
  },
  methods: {
    async fetchOrderList() {
      this.loading = true
      try {
        let apiUrl = 'http://47.94.6.186:3001/admin/order/list'
        let params = {
          page: this.currentPage,
          pageSize: this.pageSize
        }

        // 如果选择了特定状态，使用状态列表API
        if (this.currentStatus !== null) {
          apiUrl = 'http://47.94.6.186:3001/admin/order/statusList'
          params.status = this.currentStatus
        }

        const res = await axios.get(apiUrl, {
          headers: {
            token: localStorage.getItem('loginToken'),
          },
          params
        })

        console.log('订单数据:', res.data.data)

        // 如果API返回分页数据
        if (res.data.data && typeof res.data.data === 'object' && res.data.data.list) {
          this.list = res.data.data.list
          this.totalCount = res.data.data.total || res.data.data.list.length
        } else {
          // 如果API返回的是数组，进行前端分页
          const allData = res.data.data || []
          this.totalCount = allData.length
          const startIndex = (this.currentPage - 1) * this.pageSize
          const endIndex = startIndex + this.pageSize
          this.list = allData.slice(startIndex, endIndex)
        }

        this.totalPages = Math.ceil(this.totalCount / this.pageSize)

        // 更新状态统计
        this.updateStatusCounts()

      } catch (error) {
        console.error('获取订单列表失败:', error)
        this.list = []
        this.totalCount = 0
        this.totalPages = 0
        if (error.response?.status === 401) {
          alert('登录已过期，请重新登录')
          this.$router.push('/login')
        }
      } finally {
        this.loading = false
      }
    },

    async updateStatusCounts() {
      try {
        // 获取所有状态的订单数量
        for (let status of [null, 0, 1, 2, 3, 4]) {
          let apiUrl = 'http://47.94.6.186:3001/admin/order/list'
          let params = {}

          if (status !== null) {
            apiUrl = 'http://47.94.6.186:3001/admin/order/statusList'
            params.status = status
          }

          const res = await axios.get(apiUrl, {
            headers: {
              token: localStorage.getItem('loginToken'),
            },
            params
          })

          const data = res.data.data || []
          const count = Array.isArray(data) ? data.length : (data.total || 0)
          this.statusOptions[status].count = count
        }
      } catch (error) {
        console.error('获取状态统计失败:', error)
      }
    },

    changeStatus(status) {
      this.currentStatus = status
      this.currentPage = 1
      this.fetchOrderList()
    },

    async updateOrderStatus(orderid, newStatus) {
      try {
        const res = await axios.get('http://47.94.6.186:3001/admin/order/updateStatus', {
          headers: {
            token: localStorage.getItem('loginToken'),
          },
          params: {
            orderid: orderid,
            status: parseInt(newStatus)
          }
        })

        console.log('更新订单状态响应:', res.data)
        alert('订单状态更新成功')

        // 重新获取订单列表以刷新数据
        this.fetchOrderList()

      } catch (error) {
        console.error('更新订单状态失败:', error)
        alert('更新订单状态失败，请检查网络连接')

        // 如果更新失败，重新获取数据以恢复原状态
        this.fetchOrderList()
      }
    },

    changePage(page) {
      if (page >= 1 && page <= this.totalPages && page !== this.currentPage) {
        this.currentPage = page
        this.fetchOrderList()
      }
    },

    changePageSize() {
      this.currentPage = 1
      this.fetchOrderList()
    },

    getStatusClass(status) {
      const statusMap = {
        0: 'status-pending',
        1: 'status-paid',
        2: 'status-shipped',
        3: 'status-completed',
        4: 'status-cancelled'
      }
      return statusMap[status] || 'status-unknown'
    },

    getStatusText(status) {
      const statusMap = {
        0: '未支付',
        1: '待发货',
        2: '待收货',
        3: '待评价',
        4: '已完成'
      }
      return statusMap[status] || '未知状态'
    }
  },
  mounted() {
    this.fetchOrderList()
  },
}
</script>
<style lang="css" scoped>
.order-container {
  padding: 20px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  min-height: 100vh;
}

.page-header {
  background: white;
  padding: 25px;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  margin-bottom: 25px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-title {
  font-size: 28px;
  color: #2c3e50;
  margin: 0;
  font-weight: 700;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.order-stats {
  color: #6c757d;
  font-size: 14px;
}

.total-count {
  background: #e3f2fd;
  color: #1976d2;
  padding: 6px 12px;
  border-radius: 20px;
  font-weight: 500;
}

/* 状态筛选标签样式 */
.status-tabs {
  background: white;
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  margin-bottom: 25px;
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.status-tab {
  padding: 10px 16px;
  border: 2px solid #e1e5e9;
  background: white;
  color: #495057;
  border-radius: 25px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 5px;
}

.status-tab:hover {
  border-color: #667eea;
  color: #667eea;
  background: #f8f9ff;
}

.status-tab.active {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-color: #667eea;
}

.status-count {
  background: rgba(255, 255, 255, 0.2);
  padding: 2px 6px;
  border-radius: 10px;
  font-size: 12px;
  font-weight: 600;
}

.status-tab.active .status-count {
  background: rgba(255, 255, 255, 0.3);
}

.order-list {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  margin-bottom: 25px;
}

.loading-state {
  text-align: center;
  padding: 60px 20px;
  color: #6c757d;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #667eea;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 16px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: #6c757d;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.list-content {
  padding: 20px;
}

.order-item {
  display: flex;
  align-items: center;
  padding: 20px;
  border: 1px solid #f1f3f4;
  border-radius: 12px;
  margin-bottom: 15px;
  transition: all 0.3s ease;
  background: #fafbfc;
}

.order-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
  background: white;
}

.order-item:last-child {
  margin-bottom: 0;
}

.order-image {
  width: 80px;
  height: 80px;
  border-radius: 8px;
  overflow: hidden;
  margin-right: 20px;
  flex-shrink: 0;
}

.order-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.order-info {
  flex: 1;
}

.product-name {
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0 0 10px 0;
  line-height: 1.4;
}

.order-details {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 8px;
}

.price {
  font-size: 18px;
  font-weight: 700;
  color: #e74c3c;
}

.status {
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 500;
}

.status-pending {
  background: #fff3cd;
  color: #856404;
}

.status-paid {
  background: #d4edda;
  color: #155724;
}

.status-shipped {
  background: #cce5ff;
  color: #004085;
}

.status-completed {
  background: #d1ecf1;
  color: #0c5460;
}

.status-cancelled {
  background: #f8d7da;
  color: #721c24;
}

.status-unknown {
  background: #e2e3e5;
  color: #383d41;
}

.order-id {
  font-size: 12px;
  color: #6c757d;
  font-family: 'Courier New', monospace;
}

.order-actions {
  margin-top: 10px;
}

.status-select {
  padding: 6px 10px;
  border: 2px solid #e1e5e9;
  border-radius: 6px;
  background: white;
  color: #495057;
  font-size: 12px;
  cursor: pointer;
  outline: none;
  transition: all 0.3s ease;
  min-width: 100px;
}

.status-select:hover {
  border-color: #667eea;
}

.status-select:focus {
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

/* 分页样式 */
.pagination-container {
  background: white;
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 15px;
}

.pagination {
  display: flex;
  align-items: center;
  gap: 8px;
}

.page-btn {
  padding: 8px 12px;
  border: 2px solid #e1e5e9;
  background: white;
  color: #495057;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s ease;
  min-width: 40px;
}

.page-btn:hover:not(:disabled) {
  border-color: #667eea;
  color: #667eea;
  background: #f8f9ff;
}

.page-btn.active {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-color: #667eea;
}

.page-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
  background: #f8f9fa;
  color: #6c757d;
}

.page-numbers {
  display: flex;
  gap: 4px;
}

.pagination-info {
  display: flex;
  align-items: center;
  gap: 15px;
  color: #6c757d;
  font-size: 14px;
}

.page-size-select {
  padding: 6px 10px;
  border: 2px solid #e1e5e9;
  border-radius: 6px;
  background: white;
  color: #495057;
  font-size: 14px;
  cursor: pointer;
  outline: none;
  transition: border-color 0.3s ease;
}

.page-size-select:focus {
  border-color: #667eea;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .order-container {
    padding: 15px;
  }

  .page-header {
    flex-direction: column;
    gap: 15px;
    text-align: center;
  }

  .status-tabs {
    justify-content: center;
  }

  .status-tab {
    font-size: 12px;
    padding: 8px 12px;
  }

  .order-item {
    flex-direction: column;
    text-align: center;
  }

  .order-image {
    margin-right: 0;
    margin-bottom: 15px;
  }

  .order-details {
    justify-content: center;
  }

  .pagination-container {
    flex-direction: column;
    gap: 20px;
  }

  .pagination {
    flex-wrap: wrap;
    justify-content: center;
  }

  .page-numbers {
    flex-wrap: wrap;
    justify-content: center;
  }
}

@media (max-width: 480px) {
  .page-title {
    font-size: 24px;
  }

  .order-image {
    width: 60px;
    height: 60px;
  }

  .product-name {
    font-size: 14px;
  }

  .price {
    font-size: 16px;
  }

  .page-btn {
    padding: 6px 10px;
    font-size: 12px;
    min-width: 35px;
  }
}
</style>
